import {
	appId,
	apiHost,
	ossHost,
	appVersion,
	signKey,
	appPlatform
} from "@/common/js/config";


//是否刷新token
let isRefreshing = true;

//请求token信息
let authorization = '';


/**
 * 发起GET请求
 * @param {String} url 请求地址
 * @param {Object} data GET参数
 */
export const get = async (url, data, header) => http({
	url: url,
	data: data,
	method: 'GET',
	header: header,
});

/**
 * 发起POST请求
 * @param {String} url 请求地址
 * @param {Object} data POST参数
 */
export const post = async (url, data, header) => http({
	url: url,
	data: data,
	method: 'POST',
	header: header,
});

/**
 * 发起http请求
 * @param {Object} params 请求参数
 */
export const http = async (params) => {

	//基础参数
	let reqData = params;

	//请求头参数
	reqData.header = Object.assign({}, await getRequestHeaderParam(), reqData.header);

	//请求模块
	reqData.url = apiHost + '/api/' + reqData.url;

	//请求数据类型
	reqData.dataType = 'json';

	//返回
	return request(reqData).then(checkResponseBody);
};


/**
 * 上传文件
 * @param {Object} params 请求参数
 */
export const upload = async (name, filePath, formData, header) => {
	//基础参数
	let reqData = {};

	//请求头参数
	reqData.header = Object.assign({}, await getRequestHeaderParam(), header);

	//请求模块
	reqData.url = ossHost + '/api/fileManage/upload';

	//上传数据
	var uploadPromise = new Promise((resolve, reject) => {
		uni.showLoading({
			title: '上传中',
			mask: true
		});
		uni.uploadFile({
			url: reqData.url,
			filePath: filePath,
			name: name,
			timeout: 5000,
			formData: formData,
			success: (res) => {
				uni.hideLoading();
				resolve(res);
			},
			fail: (err) => {
				uni.hideLoading()
				reject(err);
			}
		});
	});
	return uploadPromise.then(checkResponseBody);
};

/**
 * 获取请求头参数
 */
export const getRequestHeaderParam = async () => {
	console.log(uni.getStorageSync('CACHE_USER'));
	let args = {
		'Content-Type': 'application/json'
	};
	args.appId = appId;
	args.appSign = Math.random().toString(36).slice(-6);
	args.appSafeCode = Math.random().toString(36).slice(-64);
	args.appVersion = appVersion;
	args.authorization = uni.getStorageSync('CACHE_USER_TOKEN');
	args.appPlatform = await appPlatform();
	return args;
};

/**
 * 封装http 请求方法
 * @param {Object} params
 * @param {Number} retry 重试次数，超过5次不重试
 * @returns {Promise}
 */
const request = (params, retry = 0) => {
	uni.showLoading({
		title: '加载中',
		mask: true
	});
	return new Promise((resolve, reject) => {
		const options = {
			url: params.url,
			data: params.data,
			header: params.header,
			method: params.method,
			dataType: params.dataType,
			success: (res) => {
				uni.hideLoading();

				// 转换Json
				if (typeof res.data === 'string') {
					res.data = JSON.parse(res.data);
				}

				//根据响应状态码处理
				if (res.data.code !== undefined) {
					console.log(res.data.code);
					switch (res.data.code) {
						case 0:
							getApp().showToast(res.data.message);
							return reject(res);
						case -1:
							// 微信自动登录
							if (params.header.appPlatform === 20 || params.header.appPlatform ===
								21) {
								return authorizedLogin('', {}, false, ).then((authResolve) => {
									if (authResolve.code == 1) {
										options.header.authorization = uni.getStorageSync(
											'CACHE_USER').token;
										uni.request(options);
									}
								}).catch((authReject) => {
									return reject(res);
								});
							}
							
							// 其他情况	
							uni.showToast({
								title: '请重新登录',
								icon: 'none',
								complete: function() {
									setTimeout(() => {
										uni.redirectTo({
											url: '/pages/user/login/login'
										});
									}, 1e3);
								}
							});
							// 重新登录,后续优化
							return Promise.reject(resp.data);
					}
				} else {
					return Promise.reject(res);
				}

				// success
				res.reqData = params;
				uni.hideLoading();
				resolve(res);
			},
			fail: (err) => {
				if (retry >= 3) {
					getApp().showToast('网络异常');
					retry = 0;
					uni.hideLoading()
					reject(err);
				} else {
					setTimeout(() => {
						retry++;
						uni.request(options);
					}, 1000);
				}
			}
		};
		uni.request(options);
	})
};

/**
 * 检查响应报文是否正确，这里可针对指定异常进行统一处理
 * @param {Object} resp 请求响应体对象
 */
const checkResponseBody = (resp) => {

	console.log(resp);

	// 转换Json
	if (typeof resp.data === 'string') {
		resp.data = JSON.parse(resp.data);
	}

	//根据响应状态码处理
	if (resp.data.code !== undefined) {
		console.log(resp.data.code);
		switch (resp.data.code) {
			case 0:
				getApp().showToast(resp.data.message);
				return Promise.reject(resp.data);
			case 1:
				return Promise.resolve(resp.data);
			case 2:
				return Promise.resolve(resp.data);
			case -1:
				return Promise.resolve(resp.data);
			default:
				return Promise.reject(resp.data);
		}
	} else {
		return Promise.reject(resp.data);
	}
};


/**
 * 用户静默授权方式登录
 * @param {String} pageUrl 页面地址
 * @param {Object} pageArgs 页面参数
 * @param {Boolean} forceLogin 是否强制登录
 * @returns {Promise}
 */
export const authorizedLogin = (pageUrl = '', pageArgs = {}, forceLogin = true) => {
	return new Promise((resolve, reject) => {
		uni.login({
			success: (res) => {
				let args = {
					code: res.code
				};
				post('user/wxLogin', args).then(data => {
					console.log(data);
					uni.setStorageSync('CACHE_USER', data.data);
					uni.setStorageSync('CACHE_USER_TOKEN', data.data.token);
					getApp().globalData.checkLogin();
					resolve(data);
				}).catch(error => {
					if (forceLogin) {
						if (isRefreshing) {
							isRefreshing = false;
							goAuthorize(pageUrl, pageArgs);
						} else {
							reject(error);
						}
					} else {
						resolve(error);
					}
				})
			},
		});
	});
};